import { Navigate, useLocation } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { useEffect, useState } from "react";
import { check_login } from "../../services/login"; 
import { set_user_info } from '../../store/modules/login'; // 引入切片的action
import Loading from "../../components/Loading"

const AuthRouter = ({ children }) => {
  const { token, userInfo } = useSelector((d) => d.login);
  const dispatch = useDispatch();
  const location = useLocation();
  const [isAuthenticated, setIsAuthenticated] = useState(null);

  useEffect(() => {
    const fetchAuthAndUserInfo = async () => {
      if (!token) {
        setIsAuthenticated(false);
        dispatch(set_user_info(null)); // 无token时清空userInfo
        return;
      }

      try {
        const res = await check_login();
        if (res.code === 0) {
          setIsAuthenticated(true);
          dispatch(set_user_info(res.data)); // 使用切片的action
        } else {
          setIsAuthenticated(false);
          dispatch(set_user_info(null));
        }
      } catch (error) {
        console.error("检查登录失败：", error);
        setIsAuthenticated(false);
        dispatch(set_user_info(null));
      }
    };

    fetchAuthAndUserInfo();
  }, [token, dispatch]);

  if (isAuthenticated === null) {
    return (<Loading></Loading>);
  }

  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location.pathname }} />;
  }

  return <>{children}</>;
};

export default AuthRouter;